package com.cf.data.serve.utils;

import cn.hutool.core.util.RandomUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * @author cuixi
 * @description:
 * @date 2024/7/25
 */
public class ImageUtil {
    /**
     *   测试
     */
    public static void main(String[] args) {

    }


    /**
     * 生成缩略图
     *
     * @param oidPath 文件大小
     * @param newPath 原文件路径
     * @param smallSize 文件压缩倍数
     * @return
     */
    public static boolean imageGenerateSmall(String oidPath, String newPath, double smallSize) {
        try {
            File bigFile = new File(oidPath);
            Image image = ImageIO.read(bigFile);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            int widthSmall = (int) (width / smallSize);
            int heightSmall = (int) (height / smallSize);
            BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
            Graphics g = buffi.getGraphics();
            g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
            g.dispose();
            ImageIO.write(buffi, "jpg", new File(newPath));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 图片压缩，图片大小超过100K自动按比例压缩到100K以下
     *
     * @param fileSize 文件大小
     * @param oidPath 原文件路径
     * @param newPath 压缩后路径
     * @return
     * @throws Exception
     */
    public static boolean imageCompress(long fileSize, String oidPath, String newPath) throws Exception {
        boolean rs = true;
        int kb = 100 * 5024;
        if (fileSize > 100 * 5024) {
            int smallSize = (int) (fileSize % kb == 0 ? fileSize / kb : fileSize / kb + 1);
            double size = Math.ceil(Math.sqrt(smallSize));
            rs = ImageUtil.imageGenerateSmall(oidPath, newPath, size);
        }else {
            newPath = oidPath;
            return false;
        }
        return rs;
    }


    /**
     * 删除文件
     * @param filePathAndName 指定得路径
     */
    public static void delFile(String filePathAndName) {
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            File myDelFile = new File(filePath);
            myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 将图片转为file
     *
     * @param url 图片url
     * @return File
     * @author dyc
     * date:   2020/9/4 14:54
     */
    public static List<String> getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = RandomUtil.randomNumbers(3)+ ".jpg";
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("test_", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            String path = file.getPath();
            String replacePath = path.replace("test_", "new_");
            List<String> list = new ArrayList<>(2);
            boolean b = imageCompress(file.length(), path, replacePath);
            list.add(path);
            if (b){
                list.add(replacePath);
            }else {
                list.add(path);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
    /**
     * 得到文件流
     * @param url  网络图片URL地址
     * @return
     */
    public static byte[] getFileStream(String url){
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }


}
